package cn.jeefast.resthz.webservice.service.impl;

import cn.jeefast.common.exception.RRException;
import cn.jeefast.common.utils.PropertiesUtils;
import cn.jeefast.resthz.webservice.Encryption;
import cn.jeefast.resthz.webservice.entity.CapitalJournal;
import cn.jeefast.resthz.webservice.entity.CarFreeCarrier;
import cn.jeefast.resthz.webservice.service.CarWebService;
import cn.jeefast.resthz.webservice.util.Bean2Xml;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.dao.IMessageTransporterDAO;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.factory.ITransportClientFactory;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.impl.USendRequset;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.impl.USendResponse;
import com.wondersgroup.cuteinfo.client.exchangeserver.usersecurty.UserToken;
import java.util.Properties;
import javax.validation.Valid;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * CarWebService 无车承运人报文上传接口实现
 *
 * @author WY
 * @date 2018/9/26 0026
 */
@Service
public class CarWebServiceImpl implements CarWebService {

  private static final Logger logger = LoggerFactory.getLogger(CarWebServiceImpl.class);

  @Autowired
  private Validator validator;

  private Properties properties = PropertiesUtils.PROPERTIES
      .getProperties("config/client_demo.properties");


  /**
   * 上传无车承运路单
   */
  @Override
  public USendResponse uploadCarFreeCarrier(@Valid CarFreeCarrier carFreeCarrier) {
    try {
      String xml = Bean2Xml.getCarMessageToXML(carFreeCarrier, validator);
      System.out.println(xml);
      //读取配置文件
      String carfreeActionType = properties.getProperty("carfree_action_type");
      return sendXml(xml, carfreeActionType);
    } catch (RRException e) {
      throw new RRException(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  /**
   * 上传资金流水
   */
  @Override
  public USendResponse uploadCapitalJournal(@Valid CapitalJournal capitalJournal) {
    try {
      String xml = Bean2Xml.getCapMessageToXML(capitalJournal, validator);
      System.out.println(xml);
      //读取配置文件
      String capitalActionType = properties.getProperty("capital_action_type");
      return sendXml(xml, capitalActionType);
    } catch (RRException e) {
      throw new RRException(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 上传报文
   */
  private USendResponse sendXml(String xml, String actionType) throws Exception {

    String targetURL = properties.getProperty("targetURL");
    String securityURL = properties.getProperty("securityURL");

    IMessageTransporterDAO transporter = null;
    //首先需要通过平台的认证服务，使用物流交换代码和密码取得令牌。有两种方式，选一种即可

    //第二种方式，调用统一认证的令牌认证服务
//      UserToken token = UserTokenUtils
//          .getTicket(properties.getProperty("username"), properties.getProperty("password"),
//              properties.getProperty("resource"), properties.getProperty("authURL"));
//      token.setTokenID(Encryption.getEncryptPassword(properties.getProperty("password"),properties.getProperty("username")));

    UserToken token = new UserToken();
    token.setUsername(properties.getProperty("username"));
    System.out.println(Encryption.getEncryptPassword(properties.getProperty("password"),
        properties.getProperty("username")));
    token.setTokenID(Encryption.getEncryptPassword(properties.getProperty("password"),
        properties.getProperty("username")));

    logger.info("tokenid:" + token.getTokenID());

    //接下来需要设置目标地址，发送报文的内容，包括报文类型Actiontype和具体报文xml
    USendRequset sendReq = new USendRequset();
    sendReq.setToaddress(properties.getProperty("toaddress").split(","));

    sendReq.setSendRequestTypeXML(actionType, xml);

    //最后，调用平台提供的发送服务发送报文
    transporter = ITransportClientFactory.createMessageTransporter(token, targetURL);

    long start = System.currentTimeMillis();
    USendResponse response = transporter.send(sendReq);
    long end = System.currentTimeMillis();
    logger.info("发送耗时：" + (end - start) + "毫秒，报文长度" + xml.getBytes().length);

    if (response.isSendResult()) {
      logger.info("send success");
    } else {
      //错误的情况下，会返回异常代码以及异常信息。异常代码请参照《3.2 共建指导性文件：交换接入》中的异常代码信息
      logger.info("send error");
      logger.info(response.getGenericFault().getCode());
      logger.info(response.getGenericFault().getMessage());
    }
    return response;
  }
}


